var addflag = $('#add_flag').val();
var xmdm = $('#xmdm').val();
var xmmc = $('#xmmc').val();
var xmms = $('#xmms').val();
var _staticHtml={};

var fldm = "";

$(function () {
    if(addflag == 1){
        $.ajax({
            type: "GET",
            url: "xmgl/getNewXmdm" ,
            success: function (data) {
                $('#xmdmInput').val(data.xmdm);
            }
        });
    } else if(addflag == 0) {
        $('#xmdmInput').val(xmdm);
        $('#xmmcInput').val(xmmc);
        $('#xmmsInput').val(xmms);
    } else {
        $.fn.zTree.init($("#sjjflTree"), setting, zNodes);
        sjjflTreeInit();

        sjjTableViewHandler();
        _staticHtml.dialogDiv3 = $("#dialog_div3").html();
        $("#dialog_div3").remove();
    }
});

function saveXM(){
    xmdm = $('#xmdmInput').val();
    xmmc = $('#xmmcInput').val();
    xmms = $('#xmmsInput').val();

    $.ajax({
        type: "POST",
        url: "xmgl/saveXM" ,
        data: {"addflag": addflag, "xmdm": xmdm, "xmmc": xmmc, "xmms": xmms},
        dataType: "json",
        success: function (data) {
            if(data.code == 1){
                LayerWn.showSucAlert("保存成功");

                setTimeout(function () {
                    parent.layer.closeAll()
                }, 1000);
            } else if(data.code == 0){
                LayerWn.showFailAlert(data.message);
            }
        }
    });
}

function closeDialog() {
    $(".layui-layer-close").eq(-1).click();
}

function sjjflTreeInit(){
    $.ajax({
        type: "POST",
        url: "xmgl/querySjjflTree" ,
        data: {"xmdm": xmdm},
        dataType: "json",
        success: function (jsonData) {
            if (jsonData.code == 200) {
                $.fn.zTree.init($("#sjjflTree"), setting, jsonData.sjjflTreeList);

                var treeObj = $.fn.zTree.getZTreeObj("sjjflTree");
                var nodes = treeObj.getNodes();

                if (nodes.length>0) {
                    //默认展开一级节点
                    if(nodes[0].children.length>0){
                        treeObj.expandNode(nodes[0], true, false, true);
                    }
                    //默认选中根节点
                    // treeObj.selectNode(treeObj.getNodes()[0]);
                }
            }
        }
    });
}

function sjjTableViewHandler() {
    var searchVal = $('#sjjSearchInput').val();

    $("#sjjTable").bootstrapTable('destroy').bootstrapTable({
        method:"POST",
        dataType:"json",
        url:"xmgl/querySjjTable",
        contentType:"application/x-www-form-urlencoded",
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true,                   //是否显示分页（*）
        sortable: false,                     //是否启用排序
        sortOrder: "asc",                   //排序方式
        queryParamsType : "undefined",
        //查询参数,每次调用是会带上这个参数，可自定义
        queryParams: function(params)
        {
            var param = {};
            param["searchVal"] = searchVal;
            param["xmdm"] = xmdm;
            param["fldm"] = fldm;
            param["pageSize"] = params.pageSize;
            param["pageNumber"] = params.pageNumber;
            return param;
        },
        sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,                       //初始化加载第一页，默认第一页
        pageSize: 10,                       //每页的记录行数（*）
        pageList: [10, 20, 50],        //可供选择的每页的行数（*）
        height: 385,
        search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
        strictSearch: false,
        showColumns: false,                  //是否显示所有的列
        showRefresh: false,                  //是否显示刷新按钮
        minimumCountColumns: 2,             //最少允许的列数
        clickToSelect: true,                //是否启用点击选中行
        uniqueId: "XH",                     //每一行的唯一标识，一般为主键列
        showToggle: false,                    //是否显示详细视图和列表视图的切换按钮
        cardView: false,                    //是否显示详细视图
        detailView: false,                   //是否显示父子表
        columns: [
            {
                field: 'sjjmc',
                title: '数据集名称',
                align: 'center'
            }, {
                field: 'sjjdm',
                title: '数据集代码',
                align: 'center'
            }, {
                field: 'sjjflmc',
                title: '数据集分类',
                align: 'center'
            }, {
                field: 'sjkbm',
                title: '数据库表名',
                align: 'center'
            }, {
                field: 'bbh',
                title: '版本号',
                align: 'center'
            }, {
                field: 'sjjdm',
                title: '操作',
                align: 'center',
                formatter: function (value, row, index) {
                    var returnStr = '<span class="text-primary" onclick="sjyList(this)" sjjdm="'+value+'" style="cursor: pointer; color: #337ab7;">数据元目录</span>';
                    returnStr += '<span class="text-primary" onclick="delSjj(this)" lsh="'+row.lsh+'" sjjmc="'+row.sjjmc+'" style="margin:0 10px; cursor: pointer; color: #337ab7;">删除</span>';
                    return returnStr;
                }
            }
        ]
    });
}

function openSjjImportWin() {
    var html = '<div style="padding: 0 20px;">' +
        '<input id="xmdm" type="hidden" value="' + xmdm + '"/>' +
        '<link href="../../../../../../sjzc-common/src/main/resources/static/css/plugins/bootstrap-table/bootstrap-table.min.css" rel="stylesheet">' +
        '<script type="text/javascript" src="plugins/bootstrap-table/bootstrap-table.min.js"></script>' +
        '<script type="text/javascript" src="plugins/bootstrap-table/bootstrap-table-mobile.min.js"></script>' +
        '<script type="text/javascript" src="plugins/bootstrap-table/locale/bootstrap-table-zh-CN.min.js"></script>' +
        '<script type="text/javascript" src="platcommon/layer-wn.js?v=1.0.0"></script>' +
        '<script src="psms-xmgl-import.js"></script>' +
        _staticHtml.dialogDiv3 + '</div>';

    var index = layer.open({
        type: 1,
        title: '导入数据集标准',
        area: ['800px', '560px'],
        shadeClose: false, //点击遮罩关闭
        scrollbar: true,//禁止浏览器滚动
        maxmin: false,
        content: html,
        end: function () {
            sjjflTreeInit();
            sjjTableViewHandler();
        }
    });
}

var setting = {
    view: {
        addHoverDom: addHoverDom,
        removeHoverDom: removeHoverDom,
        selectedMulti: false,
        showIcon:false

    },
    data: {
        simpleData: {
            enable: true
        }
    },
    callback: {
        onClick: treeOnClick
    }

};
function treeOnClick(event, treeId, treeNode, clickFlag) {
    fldm = treeNode.id;
    sjjTableViewHandler();
}

var zNodes = [{}];

//***************************ztree 点击样式 *************
var newCount = 1;
function addHoverDom(treeId, treeNode) {
    var sObj = $("#" + treeNode.tId + "_span");
    if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
    var addStr = "<span class='button add' id='addBtn_" + treeNode.tId + "' title='add node' onfocus='this.blur();'></span>";
    sObj.after(addStr);
    var btn = $("#addBtn_" + treeNode.tId);
    if (btn) btn.bind("click",
        function () {
            var zTree = $.fn.zTree.getZTreeObj("sjjflTree");
            zTree.addNodes(treeNode, {
                id: (100 + newCount),
                pId: treeNode.id,
                name: "new node" + (newCount++)
            });
            return false;
        });
}

function removeHoverDom(treeId, treeNode) {
    $("#addBtn_" + treeNode.tId).unbind().remove();
}

//***************************ztree 点击样式 *************

function delSjj(obj) {
    var lsh = $(obj).attr('lsh');
    var sjjmc = $(obj).attr('sjjmc');
    LayerWn.showConfirm("确定删除数据集"+sjjmc+"？", function () {
        $.ajax({
            type: "POST",
            url: "xmgl/delSjj" ,
            data: {"lsh": lsh},
            dataType: "json",
            success: function (data) {
                if(data.code == "200"){
                    LayerWn.showSucAlert("删除成功");
                    sjjflTreeInit();
                    sjjTableViewHandler();
                }
            }
        });
    });
}

function updateVersion() {
    LayerWn.showConfirm("确认将" + xmmc + "项目使用的所有数据集升级到最新版本？", function () {
        $.ajax({
            type: "POST",
            url: "xmgl/updateVersion" ,
            data: {"xmdm": xmdm},
            dataType: "json",
            success: function (data) {
                if(data.code == "200"){
                    LayerWn.showSucAlert("更新成功");
                    sjjTableViewHandler();
                }
            }
        });
    });
}

function sjyList(obj) {
    var sjjdm = $(obj).attr("sjjdm");
    LayerWn.openDialog('数据元信息', 'psms-sjjgl-sjyml.html?sjjdm='+sjjdm+'&hideFlag=1', 1030, 600);
}